package com.mvc.service.notice.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.huangqj.consant.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.dao.BaseDaoI;
import com.mvc.dao.mapper.NoticeDao;
import com.mvc.framework.constant.GlobalConstant;
import com.mvc.framework.spring.support.BaseServiceImpl;
import com.mvc.model.notice.Tnotice;
import com.mvc.service.notice.NoticeServiceI;
/**
 * 公告栏接口实现
 * @author qingjie
 * Date：2015-10-12
 */
@Service
public class NoticeServiceImpl extends BaseServiceImpl  implements NoticeServiceI {
	
	//使用mybatis
	@Autowired
	private NoticeDao noticeDao;
	
	//使用hibernate
	@Resource
	private BaseDaoI<Tnotice> baseDaoI;
	
	/**
	 * 获取所有公告记录
	 */
	@Override
	public List<Object> getAllNotice() {
		return noticeMap(noticeDao.getAllNotice());
	}

	/**
	 * 获取前几条记录
	 */
	@Override
	public  List<Object> getNotice() {
		return noticeMap(noticeDao.getNotice());
	}
	
	/**
	 * 重新装配公告信息
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public List<Object> noticeMap(List<Tnotice> list){
		List<Object> l = new ArrayList<Object>();
		for(Tnotice t : list){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("title", t.getTitle());
			map.put("date", ValidatorUtil.dateFormat.format(t.getDate()));
			map.put("url", t.getUrl());
			map.put("id", t.getId());
			Date date = t.getDate();
			Long diff = GlobalConstant.DATE.getTime() - date.getTime();
			Long days = diff/(1000*60*60*24);
			map.put("isNew", days);//判断当前时间是否大约发布时间天
			l.add(map);
		}
		return l;
	}

	@Override
	public Tnotice getNoticeById(Tnotice notice) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", notice.getId());
		Tnotice nTnotice = baseDaoI.get("from Tnotice n where n.id = :id", params);
		return nTnotice;
	}

	/**
	 * 新增公告
	 */
	@Override
	public void add(Tnotice notice) {
		if(notice != null){
			notice.setDate(new Date());
			notice.setNoticeType("0");
			baseDaoI.save(notice);
		}
	}

	/**
	 * 编辑公告
	 */
	@Override
	public void edit(Tnotice notice) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 删除公告
	 */
	@Override
	public Boolean delete(Long id) {
		try {
			Tnotice notice = new Tnotice();
			notice.setId(id);
			baseDaoI.delete(notice);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
